package com.example.yls.demoa;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.yls.demoa.Student;

import java.util.ArrayList;


public class StuAdapter extends BaseAdapter {
    private Context context;
    private ArrayList<Student> studentArrayList;
    private IOnDelListener listener;


    public StuAdapter(Context context, ArrayList<Student> studentArrayList,IOnDelListener listener){
        this.context=context;
        this.studentArrayList=studentArrayList;
        this.listener=listener;
    }
    public int getCount() {
        return studentArrayList.size();
    }

    @Override
    public Object getItem(int i) {
        return i;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }


    int count=0;

    public View getView(final int i, View view, ViewGroup viewGroup) {
        Log.e("StuAdapter","getview"+i+"count="+count);
        // 先判断view是不是空 非空可以复用 不需要重新构建 节省内存
        if(view==null){
            count++;
            LayoutInflater layoutInflater=LayoutInflater.from(context);
            view=layoutInflater.inflate(R.layout.list_item,viewGroup,false);

            //使用Holder保存子组件，避免每次使用时重复find
            StuViewHolder holder=new StuViewHolder();
            holder.headImg=view.findViewById(R.id.Stu_img);
            holder.nameView=view.findViewById(R.id.Stu_name);
            holder.ageView=view.findViewById(R.id.Stu_age);
            holder.del=view.findViewById(R.id.Img_del);

            view.setTag(holder);
        }





        Student stu=studentArrayList.get(i);

        StuViewHolder holder=(StuViewHolder)view.getTag();

        holder.headImg.setImageResource(stu.getImgId());
        holder.nameView.setText(stu.getName());
        holder.ageView.setText(String.valueOf(stu.getAge()));

        holder.del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //让MainActivity删除第i个学生
                listener.del(i);
            }
        });

        return view;
    }
}
